'use strict'

let watermark = {}

let setWatermark = (id, str) => {
    let childId = id + "_watermark";

    //找到父元素
    let parent = document.getElementById(id);
    //找到子元素
    let child = document.getElementById(childId);

    let myDate = new Date();
    // console.log(myDate.toLocaleString())

    // var time = myDate.toLocaleDateString().split('/').join('-');
    // let d = new Date();

    // let datetime = d.getFullYear()+"-"+(d.getMonth()+1)+"-"+d.getDate();

    if (parent !== null) {
        if (child !== null) {
            //将子元素从父元素中删除
            parent.removeChild(child);
        }
        let can = document.createElement('canvas')
        can.width = 260
        can.height = 220

        let cans = can.getContext('2d')
        cans.rotate(-20 * Math.PI / 180)
        cans.font = '14px Vedana'
        cans.fillStyle = 'rgba(200, 200, 200, 0.50)'
        cans.textAlign = 'left'
        cans.textBaseline = 'Middle'
        cans.fillText(str, 0, 120)
        cans.fillText(myDate.toLocaleString(),  0, 100);

        let div = document.createElement('div')
        div.id = childId
        div.style.pointerEvents = 'none'
        div.style.top = '70px'
        div.style.left = '0px'
        div.style.position = 'fixed'
        div.style.zIndex = '100000'
        div.style.width = document.documentElement.clientWidth - 100 + 'px'
        div.style.height = document.documentElement.clientHeight - 100 + 'px'
        div.style.background = 'url(' + can.toDataURL('image/png') + ') left top repeat'
        parent.appendChild(div)

    }

    return id;
}

// 该方法只允许调用一次
watermark.set = (id, str) => {
    id = setWatermark(id, str)
    // setInterval(() => {
    //     if (document.getElementById(id) === null) {
    //         setWatermark(id, str)
    //     }
    // }, 500)
    window.onresize = () => {
        id = setWatermark(id, str)
    }
}

export default watermark
